package fwx.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

@WebFilter(filterName = "/IllegalFilter", urlPatterns = "/*")
public class IllegalFilter implements Filter {

    /**
     * Default constructor.
     */
    public IllegalFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        ClassLoader classLoader = req.getClass().getClassLoader();
        Class<?>[] interfaces = req.getClass().getInterfaces();
        // 创建InvocationHandler接口的实例。此处使用匿名内部类来创建
        InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 只增强getParameter()
                if (method.getName().equals("getParameter")) {
                    // 调用原有的getParameter()获取参数值
                    req.setCharacterEncoding("utf-8");
                    String text = (String) method.invoke(req, args);
                    // System.out.println("text"+CommonFun.stringEncodeing(text));

                    // 检查是否有敏感词汇
                    Object obj = req.getServletContext().getAttribute("illegal_list");
                    ArrayList<String> list = (ArrayList<String>) obj;
                    // System.out.println(list);
                    for (String word : list) {
                        if (text.contains(word)) {
                            // 用一个*替换一个字符
                            String replac = "";
                            for (int i = 0; i < word.length(); i++) {
                                replac += "*";
                            }
                            // 替换所有匹配
                            text = text.replaceAll(word, replac);
                        }
                    }

                    return text;
                }

                // 如果调用的是getParameter（）,执行到前面的return就结束了，不会执行到此
                // 如果调用的不是getParameter()，就调用原方法，不做修改
                Object returnValue = method.invoke(req, args); // 调用目标方法
                return returnValue;
            }
        };

        // 创建req的代理对象
        Object proxyInstance = Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
        // 强转为ServletRequest
        ServletRequest reqProxyInstance = (ServletRequest) proxyInstance;

        // 传入req的代理对象
        chain.doFilter(reqProxyInstance, resp);

    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        InputStream in = IllegalFilter.class.getResourceAsStream("illegal.txt");
        InputStreamReader isr = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(isr);
        List<String> list = new ArrayList<String>();
        String str = null;
        while (true) {
            try {
                str = br.readLine();

                if (str != null) {
                    list.add(str);
                    // System.out.println(CommonFun.stringEncodeing(str));
                    // System.out.println(str+" "+CommonFun.stringEncodeing(str));
                } else {
                    break;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        fConfig.getServletContext().setAttribute("illegal_list", list);

    }
}
